package com.campsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campsys.entity.User;
import com.campsys.entity.CampClassTeacher;
import com.campsys.mapper.UserMapper;
import com.campsys.mapper.CampClassTeacherMapper;
import com.campsys.service.TeacherService;
import com.campsys.service.dto.TeacherDTO;
import com.campsys.service.dto.TeacherQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class TeacherServiceImpl implements TeacherService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CampClassTeacherMapper classTeacherMapper;
    
    @Override
    public IPage<User> getTeacherList(Page<User> page, TeacherQueryDTO queryDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRoleType, 2);  // 2-教师角色
        
        // 添加查询条件
        if (StringUtils.isNotBlank(queryDTO.getUsername())) {
            wrapper.like(User::getUsername, queryDTO.getUsername());
        }
        if (StringUtils.isNotBlank(queryDTO.getRealName())) {
            wrapper.like(User::getRealName, queryDTO.getRealName());
        }
        if (StringUtils.isNotBlank(queryDTO.getPhone())) {
            wrapper.like(User::getPhone, queryDTO.getPhone());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(User::getStatus, queryDTO.getStatus());
        }
        
        wrapper.orderByDesc(User::getCreateTime);
        return userMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public void addTeacher(TeacherDTO teacherDTO) {
        // 验证必填字段
        if (StringUtils.isBlank(teacherDTO.getPassword())) {
            throw new IllegalArgumentException("新增教师时密码不能为空");
        }
        
        // 验证用户名是否已存在
        if (isUsernameExists(teacherDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 验证手机号是否已存在
        if (isPhoneExists(teacherDTO.getPhone())) {
            throw new IllegalArgumentException("手机号已存在");
        }
        
        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(teacherDTO, user);
        user.setRoleType(2);  // 2-教师角色
        user.setCreateTime(LocalDateTime.now());
        
        userMapper.insert(user);
    }
    
    @Override
    @Transactional
    public void updateTeacher(TeacherDTO teacherDTO) {
        // 验证用户是否存在
        User existingUser = userMapper.selectById(teacherDTO.getId());
        if (existingUser == null || existingUser.getRoleType() != 2) {
            throw new IllegalArgumentException("教师不存在");
        }
        
        // 验证用户名是否已被其他用户使用
        if (!StringUtils.equals(existingUser.getUsername(), teacherDTO.getUsername())) {
            LambdaQueryWrapper<User> usernameWrapper = new LambdaQueryWrapper<>();
            usernameWrapper.eq(User::getUsername, teacherDTO.getUsername());
            if (userMapper.selectCount(usernameWrapper) > 0) {
                throw new IllegalArgumentException("用户名已存在");
            }
        }
        
        // 验证手机号是否已被其他用户使用
        if (!StringUtils.equals(existingUser.getPhone(), teacherDTO.getPhone())) {
            LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(User::getPhone, teacherDTO.getPhone());
            if (userMapper.selectCount(phoneWrapper) > 0) {
                throw new IllegalArgumentException("手机号已存在");
            }
        }
        
        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(teacherDTO, user);
        user.setRoleType(2);  // 确保角色类型不变
        user.setUpdateTime(LocalDateTime.now());
        
        // 如果密码为空，保持原密码不变
        if (StringUtils.isBlank(teacherDTO.getPassword())) {
            user.setPassword(existingUser.getPassword());
        }
        
        userMapper.updateById(user);
    }
    
    @Override
    @Transactional
    public void deleteTeacher(Long id) {
        // 验证教师是否存在
        User user = userMapper.selectById(id);
        if (user == null || user.getRoleType() != 2) {
            throw new IllegalArgumentException("教师不存在");
        }
        
        // 检查教师是否有关联的班级
        LambdaQueryWrapper<CampClassTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CampClassTeacher::getTeacherId, id);
        if (classTeacherMapper.selectCount(wrapper) > 0) {
            throw new IllegalArgumentException("该教师已关联教学班，无法删除");
        }
        
        userMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("无效的状态值");
        }
        
        // 验证教师是否存在
        User user = userMapper.selectById(id);
        if (user == null || user.getRoleType() != 2) {
            throw new IllegalArgumentException("教师不存在");
        }
        
        // 如果要禁用教师，检查是否有正在进行的班级
        if (status == 0) {
            LambdaQueryWrapper<CampClassTeacher> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CampClassTeacher::getTeacherId, id)
                  .eq(CampClassTeacher::getStatus, 1);  // 1-正常状态
            if (classTeacherMapper.selectCount(wrapper) > 0) {
                throw new IllegalArgumentException("该教师有正在进行的教学班，无法禁用");
            }
        }
        
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setStatus(status);
        updateUser.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(updateUser);
    }
    
    private boolean isUsernameExists(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectCount(wrapper) > 0;
    }
    
    private boolean isPhoneExists(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return userMapper.selectCount(wrapper) > 0;
    }
} 